home *** CD-ROM | disk | FTP | other *** search
/ MacHack 2000 / MacHack 2000.toast / pc / The Hacks / MacHacksBug / Python 1.5.2c1 / Extensions / Imaging / PIL / OleFileIO.py < prev    next >
Encoding:
Python Source  |  2000-06-23  |  12.7 KB  |  510 lines

  1. #
  2. # THIS IS WORK IN PROGRESS
  3. #
  4. # The Python Imaging Library
  5. # $Id: OleFileIO.py,v 1.1.1.2 1999/01/13 09:40:17 sjoerd Exp $
  6. #
  7. # stuff to deal with OLE2 Structured Storage files.  this module is
  8. # used by PIL to read Image Composer and FlashPix files, but can also
  9. # be used to read other files of this type.
  10. #
  11. # History:
  12. # 97-01-20 fl    Created
  13. # 97-01-22 fl    Fixed 64-bit portability quirk
  14. #
  15. # Notes:
  16. # FIXME: change filename to use "a/b/c" instead of ["a", "b", "c"]
  17. # FIXME: provide a glob mechanism function (using fnmatchcase)
  18. #
  19. # Literature:
  20. #
  21. # "FlashPix Format Specification, Appendix A", Kodak and Microsoft,
  22. #  September 1996.
  23. #
  24. # Quotes:
  25. # "If this document and functionality of the Software conflict,
  26. #  the actual functionality of the Software represents the correct
  27. #  functionality" -- Microsoft, in the OLE format specification
  28. #
  29. # Copyright (c) Secret Labs AB 1997.
  30. # Copyright (c) Fredrik Lundh 1997.
  31. #
  32. # See the README file for information on usage and redistribution.
  33. #
  34.  
  35.  
  36. import string, StringIO
  37.  
  38.  
  39. def i16(c, o = 0):
  40.     return ord(c[o])+(ord(c[o+1])<<8)
  41.  
  42. def i32(c, o = 0):
  43.     return ord(c[o])+(ord(c[o+1])<<8)+(ord(c[o+2])<<16)+(ord(c[o+3])<<24)
  44.  
  45.  
  46. MAGIC = '\320\317\021\340\241\261\032\341'
  47.  
  48. #
  49. # --------------------------------------------------------------------
  50. # property types
  51.  
  52. VT_EMPTY=0; VT_NULL=1; VT_I2=2; VT_I4=3; VT_R4=4; VT_R8=5; VT_CY=6;
  53. VT_DATE=7; VT_BSTR=8; VT_DISPATCH=9; VT_ERROR=10; VT_BOOL=11;
  54. VT_VARIANT=12; VT_UNKNOWN=13; VT_DECIMAL=14; VT_I1=16; VT_UI1=17;
  55. VT_UI2=18; VT_UI4=19; VT_I8=20; VT_UI8=21; VT_INT=22; VT_UINT=23;
  56. VT_VOID=24; VT_HRESULT=25; VT_PTR=26; VT_SAFEARRAY=27; VT_CARRAY=28;
  57. VT_USERDEFINED=29; VT_LPSTR=30; VT_LPWSTR=31; VT_FILETIME=64;
  58. VT_BLOB=65; VT_STREAM=66; VT_STORAGE=67; VT_STREAMED_OBJECT=68;
  59. VT_STORED_OBJECT=69; VT_BLOB_OBJECT=70; VT_CF=71; VT_CLSID=72;
  60. VT_VECTOR=0x1000;
  61.  
  62. # map property id to name (for debugging purposes)
  63.  
  64. VT = {}
  65. for k, v in vars().items():
  66.     if k[:3] == "VT_":
  67.     VT[v] = k
  68.  
  69. #
  70. # --------------------------------------------------------------------
  71. # Some common document types (root.clsid fields)
  72.  
  73. WORD_CLSID = "00020900-0000-0000-C000-000000000046"
  74.  
  75.  
  76. #
  77. # --------------------------------------------------------------------
  78.  
  79. class _OleStream(StringIO.StringIO):
  80.  
  81.     """OLE2 Stream
  82.  
  83.     Returns a read-only file object which can be used to read
  84.     the contents of a OLE stream.  To open a stream, use the
  85.     openstream method in the OleFile class.
  86.  
  87.     This function can be used with either ordinary streams,
  88.     or ministreams, depending on the offset, sectorsize, and
  89.     fat table arguments.
  90.     """
  91.  
  92.     # FIXME: should store the list of sects obtained by following
  93.     # the fat chain, and load new sectors on demand instead of
  94.     # loading it all in one go.
  95.  
  96.     def __init__(self, fp, sect, size, offset, sectorsize, fat):
  97.  
  98.     data = []
  99.  
  100.     while sect != 0xFFFFFFFE:
  101.         fp.seek(offset + sectorsize * sect)
  102.         data.append(fp.read(sectorsize))
  103.         sect = fat[sect]
  104.  
  105.     data = string.join(data, "")
  106.  
  107.     # print len(data), size
  108.  
  109.     StringIO.StringIO.__init__(self, data[:size])
  110.  
  111. #
  112. # --------------------------------------------------------------------
  113.  
  114. # FIXME: should add a counter in here to avoid looping forever
  115. # if the tree is broken.
  116.  
  117. class _OleDirectoryEntry:
  118.  
  119.     """OLE2 Directory Entry
  120.  
  121.     Encapsulates a stream directory entry.  Note that the
  122.     constructor builds a tree of all subentries, so we only
  123.     have to call it with the root object.
  124.     """
  125.  
  126.     def __init__(self, sidlist, sid):
  127.  
  128.     # store directory parameters.  the caller provides
  129.     # a complete list of directory entries, as read from
  130.     # the directory stream.
  131.  
  132.     name, type, sect, size, sids, clsid = sidlist[sid]
  133.  
  134.     self.sid  = sid
  135.     self.name = name
  136.     self.type = type # 1=storage 2=stream
  137.     self.sect = sect
  138.     self.size = size
  139.     self.clsid = clsid
  140.  
  141.     # process child nodes, if any
  142.  
  143.     self.kids = []
  144.  
  145.     sid = sidlist[sid][4][2]
  146.  
  147.     if sid != -1:
  148.  
  149.         # the directory entries are organized as a red-black tree.
  150.         # the following piece of code does an ordered traversal of
  151.         # such a tree (at least that's what I hope ;-)
  152.  
  153.         stack = [self.sid]
  154.  
  155.         # start at leftmost position
  156.  
  157.         left, right, child = sidlist[sid][4]
  158.  
  159.         while left != 0xFFFFFFFF:
  160.         stack.append(sid)
  161.         sid = left
  162.         left, right, child = sidlist[sid][4]
  163.  
  164.         while sid != self.sid:
  165.  
  166.         self.kids.append(_OleDirectoryEntry(sidlist, sid))
  167.  
  168.         # try to move right
  169.         left, right, child = sidlist[sid][4]
  170.         if right != 0xFFFFFFFF:
  171.             # and then back to the left
  172.             sid = right
  173.             while 1:
  174.             left, right, child = sidlist[sid][4]
  175.             if left == 0xFFFFFFFF:
  176.                 break
  177.             stack.append(sid)
  178.             sid = left
  179.         else:
  180.             # couldn't move right; move up instead
  181.             while 1:
  182.             ptr = stack[-1]
  183.             del stack[-1]
  184.             left, right, child = sidlist[ptr][4]
  185.             if right != sid:
  186.                 break
  187.             sid = right
  188.             left, right, child = sidlist[sid][4]
  189.             if right != ptr:
  190.                 sid = ptr
  191.  
  192.         # in the OLE file, entries are sorted on (length, name).
  193.         # for convenience, we sort them on name instead.
  194.  
  195.         self.kids.sort()
  196.  
  197.     def __cmp__(self, other):
  198.     "Compare entries by name"
  199.  
  200.     return cmp(self.name, other.name)
  201.  
  202.     def dump(self, tab = 0):
  203.     "Dump this entry, and all its subentries (for debug purposes only)"
  204.  
  205.     TYPES = ["(invalid)", "(storage)", "(stream)", "(lockbytes)",
  206.          "(property)", "(root)"]
  207.  
  208.     print " "*tab + repr(self.name), TYPES[self.type],
  209.     if self.type in (2, 5):
  210.         print self.size, "bytes",
  211.     print
  212.     if self.type in (1, 5) and self.clsid:
  213.         print " "*tab + "{%s}" % self.clsid
  214.  
  215.     for kid in self.kids:
  216.         kid.dump(tab + 2)
  217.  
  218. #
  219. # --------------------------------------------------------------------
  220.  
  221. class OleFileIO:
  222.     """OLE container object
  223.  
  224.     This class encapsulates the interface to an OLE 2 structured
  225.     storage file.  Use the listdir and openstream methods to access
  226.     the contents of this file.
  227.  
  228.     Object names are given as a list of strings, one for each subentry
  229.     level.  The root entry should be omitted.  For example, the following
  230.     code extracts all image streams from a Microsoft Image Composer file:
  231.  
  232.     ole = OleFileIO("fan.mic")
  233.  
  234.     for entry in ole.listdir():
  235.         if entry[1:2] == "Image":
  236.         fin = ole.openstream(entry)
  237.         fout = open(entry[0:1], "wb")
  238.         while 1:
  239.             s = fin.read(8192)
  240.             if not s:
  241.             break
  242.             fout.write(s)
  243.  
  244.     You can use the viewer application provided with the Python Imaging
  245.     Library to view the resulting files (which happens to be standard
  246.     TIFF files).
  247.     """
  248.  
  249.     def __init__(self, filename = None):
  250.  
  251.     if filename:
  252.         self.open(filename)
  253.  
  254.     def open(self, filename):
  255.     """Connect to a OLE2 file"""
  256.  
  257.     if type(filename) == type(""):
  258.         self.fp = open(filename, "rb")
  259.     else:
  260.         self.fp = filename
  261.  
  262.     header = self.fp.read(512)
  263.     
  264.     if len(header) != 512 or header[:8] != MAGIC:
  265.         raise IOError, "not an OLE2 structured storage file"
  266.  
  267.     # file clsid (probably never used, so we don't store it)
  268.     clsid = self._clsid(header[8:24])
  269.  
  270.     # FIXME: could check version and byte order fields
  271.  
  272.     self.sectorsize = 1 << i16(header, 30)
  273.     self.minisectorsize = 1 << i16(header, 32)
  274.  
  275.     self.minisectorcutoff = i32(header, 56)
  276.  
  277.     # Load file allocation tables
  278.     self.loadfat(header)
  279.  
  280.     # Load direcory.  This sets both the sidlist (ordered by id)
  281.     # and the root (ordered by hierarchy) members.
  282.     self.loaddirectory(i32(header, 48))
  283.  
  284.     self.ministream = None
  285.     self.minifatsect = i32(header, 60)
  286.  
  287.  
  288.     def loadfat(self, header):
  289.     # Load the FAT table.  The header contains a sector numbers
  290.     # for the first 109 FAT sectors.  Additional sectors are
  291.     # described by DIF blocks (FIXME: not yet implemented)
  292.  
  293.     sect = header[76:512]
  294.     fat = []
  295.     for i in range(0, len(sect), 4):
  296.         ix = i32(sect, i)
  297.         if ix in [0xFFFFFFFE, 0xFFFFFFFF]:
  298.         break
  299.         s = self.getsect(ix)
  300.         fat = fat + map(lambda i, s=s: i32(s, i), range(0, len(s), 4))
  301.     self.fat = fat
  302.  
  303.     def loadminifat(self):
  304.     # Load the MINIFAT table.  This is stored in a standard sub-
  305.     # stream, pointed to by a header field.
  306.  
  307.     s = self._open(self.minifatsect).read()
  308.  
  309.     self.minifat = map(lambda i, s=s: i32(s, i), range(0, len(s), 4))
  310.  
  311.     def getsect(self, sect):
  312.     # Read given sector
  313.  
  314.     self.fp.seek(512 + self.sectorsize * sect)
  315.     return self.fp.read(self.sectorsize)
  316.  
  317.     def _unicode(self, s):
  318.     # Map unicode string to Latin 1
  319.  
  320.     # FIXME: some day, Python will provide an official way to handle
  321.     # Unicode strings, but until then, this will have to do...
  322.     return filter(ord, s)
  323.  
  324.     def loaddirectory(self, sect):
  325.     # Load the directory.  The directory is stored in a standard
  326.     # substream, independent of its size.
  327.  
  328.     # read directory stream
  329.     fp = self._open(sect)
  330.  
  331.     # create list of sid entries
  332.     self.sidlist = []
  333.     while 1:
  334.         entry = fp.read(128)
  335.         if not entry:
  336.         break
  337.         type = ord(entry[66])
  338.         name = self._unicode(entry[0:0+i16(entry, 64)])
  339.         ptrs = i32(entry, 68), i32(entry, 72), i32(entry, 76)
  340.         sect, size = i32(entry, 116), i32(entry, 120)
  341.         clsid = self._clsid(entry[80:96])
  342.         self.sidlist.append((name, type, sect, size, ptrs, clsid))
  343.  
  344.     # create hierarchical list of directory entries
  345.     self.root = _OleDirectoryEntry(self.sidlist, 0)
  346.  
  347.     def dumpdirectory(self):
  348.     # Dump directory (for debugging only)
  349.  
  350.     self.root.dump()
  351.  
  352.     def _clsid(self, clsid):
  353.     if clsid == "\0" * len(clsid):
  354.         return ""
  355.     return (("%08X-%04X-%04X-%02X%02X-" + "%02X" * 6) %
  356.         ((i32(clsid, 0), i16(clsid, 4), i16(clsid, 6)) +
  357.         tuple(map(ord, clsid[8:16]))))
  358.  
  359.     def _list(self, files, prefix, node):
  360.     # listdir helper
  361.  
  362.     prefix = prefix + [node.name]
  363.     for entry in node.kids:
  364.         if entry.kids:
  365.         self._list(files, prefix, entry)
  366.         else:
  367.         files.append(prefix[1:] + [entry.name])
  368.  
  369.     def _find(self, filename):
  370.     # openstream helper
  371.  
  372.     node = self.root
  373.     for name in filename:
  374.         for kid in node.kids:
  375.         if kid.name == name:
  376.             break
  377.         else:
  378.         raise IOError, "file not found"
  379.         node = kid
  380.     return node.sid
  381.  
  382.     def _open(self, start, size = 0x7FFFFFFF):
  383.     # openstream helper.
  384.  
  385.     if size < self.minisectorcutoff:
  386.         # ministream object
  387.         if not self.ministream:
  388.         self.loadminifat()
  389.         self.ministream = self._open(self.sidlist[0][2])
  390.         return _OleStream(self.ministream, start, size, 0,
  391.                   self.minisectorsize, self.minifat)
  392.  
  393.     # standard stream
  394.     return _OleStream(self.fp, start, size, 512,
  395.               self.sectorsize, self.fat)
  396.  
  397.     #
  398.     # public interface
  399.  
  400.     def listdir(self):
  401.     """Return a list of streams stored in this file"""
  402.  
  403.     files = []
  404.     self._list(files, [], self.root)
  405.     return files
  406.  
  407.     def openstream(self, filename):
  408.     """Open a stream as a read-only file object"""
  409.  
  410.     slot = self._find(filename)
  411.     name, type, sect, size, sids, clsid = self.sidlist[slot]
  412.     if type != 2:
  413.         raise IOError, "this file is not a stream"
  414.     return self._open(sect, size)
  415.  
  416.     def getproperties(self, filename):
  417.     """Return properties described in substream"""
  418.  
  419.     fp = self.openstream(filename)
  420.  
  421.     data = {}
  422.  
  423.     # header
  424.     s = fp.read(28)
  425.     clsid = self._clsid(s[8:24])
  426.  
  427.     # format id
  428.     s = fp.read(20)
  429.     fmtid = self._clsid(s[:16])
  430.     fp.seek(i32(s, 16))
  431.  
  432.     # get section
  433.     s = "****" + fp.read(i32(fp.read(4))-4)
  434.  
  435.     for i in range(i32(s, 4)):
  436.  
  437.         id = i32(s, 8+i*8)
  438.         offset = i32(s, 12+i*8)
  439.         type = i32(s, offset)
  440.  
  441.         # test for common types first (should perhaps use
  442.         # a dictionary instead?)
  443.  
  444.         if type == VT_I2:
  445.         value = i16(s, offset+4)
  446.         if value >= 32768:
  447.             value = value - 65536
  448.         elif type == VT_UI2:
  449.         value = i16(s, offset+4)
  450.         elif type in (VT_I4, VT_ERROR):
  451.         value = i32(s, offset+4)
  452.         elif type == VT_UI4:
  453.         value = i32(s, offset+4) # FIXME
  454.         elif type in (VT_BSTR, VT_LPSTR):
  455.         count = i32(s, offset+4)
  456.         value = s[offset+8:offset+8+count-1]
  457.         elif type == VT_BLOB:
  458.         count = i32(s, offset+4)
  459.         value = s[offset+8:offset+8+count]
  460.         elif type == VT_LPWSTR:
  461.         count = i32(s, offset+4)
  462.         value = self._unicode(s[offset+8:offset+8+count*2])
  463.         elif type == VT_FILETIME:
  464.         value = long(i32(s, offset+4)) + (long(i32(s, offset+8))<<32)
  465.         # FIXME: this is a 64-bit int: "number of 100ns periods
  466.         # since Jan 1,1601".  Should map this to Python time
  467.         value = value / 10000000L # seconds
  468.         elif type == VT_UI1:
  469.         value = ord(s[offset+4])
  470.         elif type == VT_CLSID:
  471.         value = self._clsid(s[offset+4:offset+20])
  472.         elif type == VT_CF:
  473.         count = i32(s, offset+4)
  474.         value = s[offset+8:offset+8+count]
  475.         else:
  476.         value = None # everything else yields "None"
  477.  
  478.         # FIXME: add support for VT_VECTOR
  479.  
  480.         #print "%08x" % id, repr(value),
  481.         #print "(%s)" % VT[i32(s, offset) & 0xFFF]
  482.  
  483.         data[id] = value
  484.  
  485.     return data
  486.  
  487. #
  488. # --------------------------------------------------------------------
  489. # This script can be used to dump the directory of any OLE2 structured
  490. # storage file.
  491.  
  492. if __name__ == "__main__":
  493.  
  494.     import sys
  495.  
  496.     for file in sys.argv[1:]:
  497.     try:
  498.         ole = OleFileIO(file)
  499.         print "-" * 68
  500.         print file
  501.         print "-" * 68
  502.         ole.dumpdirectory()
  503.         for file in ole.listdir():
  504.         if file[-1][0] == "\005":
  505.             print file
  506.             ole.getproperties(file)
  507.     except IOError:
  508.         pass
  509.